package com.example.photography.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.example.photography.R;
import com.example.photography.common.BaseActivity;
import com.example.photography.util.DownUtil;
import com.example.photography.util.Util;
import com.example.photography.view.ArrowDownloadButton;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 多线程下载
 */
public class Update_APK extends BaseActivity {

    @BindView(R.id.arrow_download_button)
    ArrowDownloadButton arrowDownloadButton;
    @BindView(R.id.install_apk)
    Button installApk;
    private DownUtil downUtil;
    private static final int UPDATE_RATE = 1;
    private static final int DOWNLOAD_APK_SUCCESS = 2;
    private static final int GET_UNKNOWN_APP_SOURCES = 3;
    private static final int DOWNLOAD_APK_FAIL = 4;
    private double completeRate;
    private boolean download_sign = true;

    @Override
    protected void initData() {
        //取消严格模式  FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        if (bundle != null) {
            String apk_url = bundle.getString("apk_url");
            arrowDownloadButton.startAnimating();
            //初始化DownUtill对象
            downUtil = new DownUtil(apk_url, 6);
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x456);
        } else {
            Util.show(Update_APK.this, "未知错误，请返回重试！");
        }
        initLister();


    }

    private void initLister() {
        installApk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //检测Android版本号
                checkOreo();
            }
        });
        arrowDownloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo 线程中断和重启待解决
                if (download_sign) {
                    download_sign = false;
                    arrowDownloadButton.reset();
                } else {
                    arrowDownloadButton.startAnimating();
                    download_sign = true;
                    synchronized (thread) {
                        thread.notifyAll();
                    }
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.update_apk;
    }

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!download_sign) {//让线程处于暂停等待状态
                onPause();
            }
            try {
                arrowDownloadButton.startAnimating();
                // 开始下载
                downUtil.download();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 定义每秒调度获取一次系统的完成进度
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 获取下载任务的完成比例
                    //todo 某些手机存在Attempt to read from field 'int com.example.photography.util.DownUtil$DownThread.length' on a null object reference
                    completeRate = downUtil.getCompleteRate();
                    handler.sendEmptyMessageDelayed(UPDATE_RATE, 0);

                    // 下载完全后取消任务调度
                    if (completeRate >= 1) {
                        timer.cancel();
                        handler.sendEmptyMessageDelayed(DOWNLOAD_APK_SUCCESS, 0);
                    }
                }
            }, 0, 100);

        }
    });

    private void checkOreo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
            //判断是否可以直接安装
            boolean canInstall = getPackageManager().canRequestPackageInstalls();
            if (canInstall) {
                //安装下载好的应用
                installAPK();
            } else {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);

            }
        } else {
            //安装apk
            installAPK();
        }
    }

    private void installAPK() {
        File apkFile = new File(Environment.getExternalStorageDirectory().toString() + "/app-debug.apk");
        if (!apkFile.exists() || apkFile.length() == 0) {
            Util.show(Update_APK.this, "文件损坏");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //安装完成后，启动app（少了这句话启动不了）
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.parse("file://" + apkFile.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
        //删除所有activity
        removeAll();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0x456 && grantResults.length == 1
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            thread.start();

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {//下载数据成功
                case DOWNLOAD_APK_SUCCESS:
                    Util.showToast(Update_APK.this, "下载完成，请点击安装~");
                    installApk.setVisibility(View.VISIBLE);//显示安装按钮

                    break;
                case DOWNLOAD_APK_FAIL:
                    Util.showToast(Update_APK.this, "联网下载数据失败~");
                    break;
                case UPDATE_RATE:
                    arrowDownloadButton.setProgress((float) completeRate * 100);
                    Log.i("rate", String.valueOf(completeRate));

            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case GET_UNKNOWN_APP_SOURCES:
                    checkOreo();
                    break;
            }
        }
    }

    //为了避免出现内存的泄漏，需要在onDestroy()中，移除所有未被执行的消息
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        handler.removeCallbacksAndMessages(null);
        //todo 移除线程
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
